package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

public class SortingActivity extends AppCompatActivity {
    private static final int REQUEST_CODE = 1;
    private static final int MESSAGE_UPDATE_TEXT = 1;
    private static final String TAG = "SortingActivity";
    // UI组件
    private Button btnDollar, btnEuro, btnWon;
    private EditText inputRmb;
    private TextView rmbResult;
    private TextView helloTextView;

    // 汇率变量
    private float dollarrate = 0.14f;
    private float eurorate = 0.13f;
    private float wonrate = 202.03f;

    // 主线程的 Handler
    private Handler handler = new Handler(msg -> {
        if (msg.what == MESSAGE_UPDATE_TEXT) {
            String message = (String) msg.obj;
            helloTextView.setText(message);
        }
        return true;
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sorting);

        // 初始化UI组件
        btnDollar = findViewById(R.id.button_dollar);
        btnEuro = findViewById(R.id.button_euro);
        btnWon = findViewById(R.id.button_won);
        inputRmb = findViewById(R.id.rmb);
        rmbResult = findViewById(R.id.Result);
        helloTextView = findViewById(R.id.hello);

        // 设置货币按钮点击事件
        btnDollar.setOnClickListener(v -> calculate(dollarrate));
        btnEuro.setOnClickListener(v -> calculate(eurorate));
        btnWon.setOnClickListener(v -> calculate(wonrate));

        // 启动子线程
        new Thread(() -> {
            try {
                // 模拟耗时操作
                Thread.sleep(2000);
                String url = "https://www.boc.cn/sourcedb/whpj/";
                Document doc = Jsoup.connect(url).get();
                Log.i(TAG, "run: " + doc.title());

                // 获取table
                Elements tables = doc.getElementsByTag("table");
                if (tables.size() > 1) {
                    Element table = tables.get(1);
                    Elements tds = table.getElementsByTag("td");
                    Elements ths = table.getElementsByTag("th");
                    int currencyIndex = -1;
                    int rateIndex = -1;
                    for (int i = 0; i < ths.size(); i++) {
                        Element th = ths.get(i);
                        String thText = th.text();
                        if ("货币名称".equals(thText)) {
                            currencyIndex = i;
                        }
                        if ("中行折算价".equals(thText)) {
                            rateIndex = i;
                        }
                    }
                    if (currencyIndex != -1 && rateIndex != -1) {
                        for (int i = 0; i < tds.size(); i += ths.size()) {
                            if (i + currencyIndex < tds.size() && i + rateIndex < tds.size()) {
                                Element currencyElement = tds.get(i + currencyIndex);
                                Element rateElement = tds.get(i + rateIndex);
                                String currency = currencyElement.text();
                                String rate = rateElement.text();
                                Log.i(TAG, "run: " + currency + "==>" + rate);
                            }
                        }
                    } else {
                        Log.e(TAG, "未找到对应的表头");
                    }
                } else {
                    Log.e(TAG, "未找到足够数量的table元素，无法定位目标table");
                }
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }
            // 发送消息到主线程
            Message msg = handler.obtainMessage();
            msg.what = MESSAGE_UPDATE_TEXT;
            msg.obj = "汇率计算";
            handler.sendMessage(msg);
        }).start();
    }

    // 统一计算方法
    private void calculate(float rate) {
        String input = inputRmb.getText().toString();
        if (input.isEmpty()) {
            Toast.makeText(this, "请输入人民币金额", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            float result = Float.parseFloat(input) * rate;
            rmbResult.setText(String.valueOf(result));
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效数字", Toast.LENGTH_SHORT).show();
        }
    }

    // 跳转到设置页面
    public void config(View view) {
        Intent intent = new Intent(this, SettingActivity.class);
        intent.putExtra("dollar_key", dollarrate);
        intent.putExtra("euro_key", eurorate);
        intent.putExtra("won_key", wonrate);
        startActivityForResult(intent, REQUEST_CODE);
    }

    // 处理返回数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            dollarrate = data.getFloatExtra("dollar_key", dollarrate);
            eurorate = data.getFloatExtra("euro_key", eurorate);
            wonrate = data.getFloatExtra("won_key", wonrate);
        }
    }
}